package com.lkd.job;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;

/**
 *自动创建补货工单
 */
@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vendingMachineService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private MqttProducer mqttProducer;

    /**
     *  @XxlJob("supplyJobTask") 括号中要与xxl-job控制台的任务 JobHandler 一致
     * @param param
     * @return
     */
        @XxlJob("supplyJobTask")
    public ReturnT<String> supplyJobTask(String param){
        log.info("收到xxl-job 参数:{}",param);
        //1.查询所有在运营的售货机
        LambdaQueryWrapper<VendingMachineEntity> eq = Wrappers.<VendingMachineEntity>lambdaQuery()
                .eq(VendingMachineEntity::getVmStatus, 1);
        List<VendingMachineEntity> machineList = vendingMachineService.list(eq);

        //2.遍历售货机集合
        machineList.stream().map(machine->{
            //2.1创建补货协议对象
            SupplyContract supplyContract = new SupplyContract();
            supplyContract.setInnerCode(machine.getInnerCode());
            //2.2获取货道集合
            List<ChannelEntity> channelList = channelService.getChannelesByInnerCode(machine.getInnerCode());
            //2.3遍历货道集合, 获得每个货道的补货信息列表
            List<SupplyChannel> supplyChannelList = getSupplyChannels(channelList);
            //2.4将补货数据封装到补货协议中
            supplyContract.setSupplyData(supplyChannelList);

            //3.返回补货协议信息
            return supplyContract;
        }).filter(supplyContract -> CollectionUtils.isNotEmpty(supplyContract.getSupplyData()))
          .forEach(supplyContract -> {
              try {
                  //4.补货信息不为空->发送消息通知emq
                  mqttProducer.send(TopicConfig.TASK_SUPPLY_TOPIC,2,supplyContract);
              } catch (JsonProcessingException e) {
                  e.printStackTrace();
                  log.error("发送自动补货工单消息失败:{}",e.getMessage());
              }
          });
        return ReturnT.SUCCESS;
    }

    /**
     * 遍历货道集合,查询到补货列表
     * @param channelList
     * @return
     */
    private List<SupplyChannel> getSupplyChannels(List<ChannelEntity> channelList) {
        List<SupplyChannel> supplyChannelList = channelList.stream()
                .filter(channel -> channel.getSkuId() != 0 && channel.getMaxCapacity() - channel.getCurrentCapacity() > 0)
                .map(channel -> {
                    SupplyChannel supplyChannel = new SupplyChannel();
                    supplyChannel.setChannelId(channel.getChannelCode());
                    supplyChannel.setCapacity(channel.getMaxCapacity() - channel.getCurrentCapacity());
                    supplyChannel.setSkuId(channel.getSkuId());
                    supplyChannel.setSkuName(channel.getSku().getSkuName());
                    supplyChannel.setSkuImage(channel.getSku().getSkuImage());
                    return supplyChannel;
                }).collect(Collectors.toList());
        return supplyChannelList;
    }
}
